package com.cenxi.common.util;

import com.cenxi.common.constants.Constants;
import com.cenxi.common.constants.UserConstants;
import com.cenxi.common.convert.MenuDTOToMenuEntity;
import com.cenxi.common.dto.resp.MenuRespDTO;
import com.cenxi.dao.domain.Menu;
import org.apache.commons.lang3.StringUtils;
import org.springframework.util.CollectionUtils;

import java.util.*;
import java.util.stream.Collectors;

/**
 * @Author cenxi
 * @Date 2023/8/19 14:31
 * @Version 1.0
 */
public class MenuUtils {

    public static List<MenuRespDTO> treeMenu(List<Menu> menus) {
        if (CollectionUtils.isEmpty(menus)) {
            return Collections.emptyList();
        }
        Map<Long, Menu> map = menus.stream().collect(Collectors.toMap(Menu::getId, Menu -> Menu));
        List<Menu> resList = new ArrayList<>();
        menus.forEach(v -> {
            v.setComponent(getComponent(v));
            if (v.getParentId() == 0) {
                resList.add(map.get(v.getId()));
            } else {
                Menu menu = map.get(v.getParentId());
                if (Objects.nonNull(menu)) {
                    menu.getChildren().add(v);
                } else {
                    resList.add(v);
                }
            }
        });
        return MenuDTOToMenuEntity.INTERFACE.entity2dto(resList);
    }

    /**
     * 获取组件信息
     *
     * @param menu 菜单信息
     * @return 组件信息
     */
    public static String getComponent(Menu menu) {
        String component = UserConstants.LAYOUT;
        if (org.apache.commons.lang3.StringUtils.isNotEmpty(menu.getComponent()) && !(menu.getParentId().intValue() == 0 && UserConstants.TYPE_MENU.equals(menu.getMenuType())
                && UserConstants.NO_FRAME.equals(String.valueOf(menu.getFrame())))) {
            component = menu.getComponent();
        } else if (org.apache.commons.lang3.StringUtils.isEmpty(menu.getComponent()) && menu.getParentId().intValue() != 0 && (UserConstants.NO_FRAME.equals(String.valueOf(menu.getFrame())) && org.apache.commons.lang3.StringUtils.startsWithAny(menu.getPath(), Constants.HTTP, Constants.HTTPS))) {
            component = UserConstants.INNER_LINK;
        } else if (StringUtils.isEmpty(menu.getComponent()) && (menu.getParentId().intValue() != 0 && UserConstants.TYPE_DIR.equals(menu.getMenuType()))) {
            component = UserConstants.PARENT_VIEW;
        }
        return component;
    }

}
